//
//  ReactAgreementViewController.swift
//  Screen
//
//  Created by Season02 on 8/18/16.
//  Copyright © 2016 alex.chih. All rights reserved.
//

import React
import Locksmith
import SwiftHTTP
import HandyJSON

var homeView : ReactHomePageViewController? = nil

class ReactHomePageViewController: UIViewController, DelegateWechatPay
{
    var rootView : RCTRootView? = nil
    
    override func viewDidLoad()
    {
        initReact()
        homeView = self
        UIApplication.shared.setStatusBarStyle(.lightContent, animated: false)
        
        TPWechat.wechatPayDele = self
    }
    
    fileprivate func initReact()
    {      
        commonController = self
        let moduleName = "home"
        
        /* -------------- TEST AREA BEGIN -------------- */
        var totalCount = 0
        for familyName in UIFont.familyNames
        {
            let familyNameArr = UIFont.fontNames(forFamilyName: familyName)
            print("familyName:\(familyName) count=\(familyNameArr.count)")
            let tempCount = familyNameArr.count
            
            totalCount += tempCount
            for fontName in familyNameArr{
                print("++++ \(fontName)")
            }
        }
        
        print("totalCount = \(totalCount)")
        /* -------------- TEST AREA END -------------- */

        let jsCodeLocation = URL(string: Reference.ReactUrl("index.ios"))
//        let jsCodeLocation = Bundle.main.url(forrResource: "index",  withExtension: "bundle")
        
        let mockData:NSDictionary = ["userId":"000111" , "controllerName":"AgreementPageLogic"]
//        et mockData:NSDictionary = ["userId":MGCSettingDone.getUserId() , "controllerName":"AgreementPageLogic"]
        
        let rootView = RCTRootView(bundleURL: jsCodeLocation, moduleName: moduleName, initialProperties: mockData as! [AnyHashable: Any] , launchOptions: nil)
//        rootView = RCTRootView(bundleURL: jsCodeLocation, moduleName: moduleName, initialProperties: nil , launchOptions: nil)
        
        let statusBarHeight = UIApplication.shared.statusBarFrame.height
//        rootView!.frame = CGRect(x: 0, y: statusBarHeight, width: self.view.bounds.width, height: self.view.bounds.height - statusBarHeight)
        rootView!.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
    
        
        self.view.addSubview(rootView!)
    }
    
    func popup()
    {
        DispatchQueue.global().async {
            DispatchQueue.main.async
                {
                    let _ = self.navigationController?.popViewController(animated: true);
                    self.navigationController?.setNavigationBarHidden(false, animated: true)
            }
        }
    }
    
    func unionRise(data:[String], callback:@escaping (Bool,ReadyToPay)->())
    {
        do
        {
            UserDefaults.standard.set(data[3] as String, forKey: Key_User_Token)
            
            let data = ["payType":data[0],"productType":data[1],"productId":data[2],"userToken":data[3]]
            
            print(data)
            
            let url = SRef.Api(api: .rise)
            
            let opt = try HTTP.GET(url, parameters: data)
            opt.start 
                { response in
                    if let err = response.error
                    {
                        print("error: \(err.localizedDescription)")
                        
                        return//also notify app of failure as needed
                    }
                    
                    let data = response.data
                    
                    let dic = try! JSONSerialization.jsonObject(with: data,
                                                                options: JSONSerialization.ReadingOptions.mutableContainers) as! NSMutableDictionary
                    
                    print("请求reAccess的response = \(data)")
//                    let rise = ["productId":data[0], "productType":data[1], "userToken":data[2], "payType":data[3]]
                    
                    let entity = JSONDeserializer<GenStatus>.deserializeFrom(dict: dic)
                    UserDefaults.standard.set(entity?.entity?["outTradeId"] as! String, forKey: Key_Out_Trade_Id)
                    
                    if (entity?.status?.contains("99"))!
                    {
                        let ready = JSONDeserializer<ReadyToPay>.deserializeFrom(dict: entity?.entity?["readyToPay"] as? NSDictionary)
                        callback(true, ready!)
                    }
                    else
                    {
                        callback(false, ReadyToPay() )
                    }
            }
        }
        catch let error
        {
            print("got an error creating the request: \(error)")
        }
    }
    
    func unionCheck(data:[String], callback:@escaping (Bool,NSDictionary)->())
    {
        do
        {
            let data = [ "userToken":data[0], "outTradeId":data[1]]
            let url = SRef.Api(api: .check)
            
            let opt = try HTTP.POST(url, parameters: data)
            opt.start
                { response in
                    if let err = response.error
                    {
                        print("error: \(err.localizedDescription)")
                        _homeModule?.finishPay(status: false)
                        return//also notify app of failure as needed
                    }
                    
                    let data = response.data
                    
                    let dic = try! JSONSerialization.jsonObject(with: data,
                                                                options: JSONSerialization.ReadingOptions.mutableContainers) as! NSMutableDictionary
                    
                    let rise = ["productId":data[0], "productType":data[1], "userToken":data[2], "payType":data[3]]
                    
                    let entity = JSONDeserializer<GenStatus>.deserializeFrom(dict: dic)
                    
                    if (entity?.status?.contains("99"))!
                    {
                        if(entity?.entity?.value(forKey: "status") as! String == "success")
                        {
                            _homeModule?.finishPay(status: true)
                        }
                        else
                        {
                            _homeModule?.finishPay(status: false)
                        }
                    }
                    else
                    {
                        _homeModule?.finishPay(status: false)
                    }
            }
        }
        catch let error
        {
            print("got an error creating the request: \(error)")
        }
    }
    
    //程序直接返回结果，如果为支付成功，我们就请求 check 加以确认
    func payDone(status:Bool)
    {
        if(status)
        {
            let out_id = UserDefaults.standard.string(forKey: Key_Out_Trade_Id)
            let token = UserDefaults.standard.string(forKey: Key_User_Token)
            
//            let data =
            
            self.unionCheck(data: [token!, out_id!], callback: { (status, dic) in
                print("")
            })
        }
        else
        {
            _homeModule?.finishPay(status: status)
        }
    }
    
}
